package hyj.qx.websocket.we;


import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/websocket/{userName}")
public class WebSocketServer {
    private static Map<String,WebSocketServer> onlineUsers = new ConcurrentHashMap<>();
    Map<String ,Session> sessionCache = new HashMap<>();
    // sessionId对应的用户名
    Map<String,String> sessionUserName = new HashMap<>();
    private HttpSession httpSession;
    @OnOpen
    public void onOpen(Session session, EndpointConfig config , @PathParam("userName") String userName) {
        String sessionId = session.getId();
        // 将session放入缓存
        sessionCache.put(sessionId,session);
        // 将用户名和sessionid对应起来
        sessionUserName.put(sessionId,userName);
        System.out.println("连接成功,用户名："+userName);

    }
    @OnMessage
    public void onMessage(String message,Session session) {
        String sessionId = session.getId();
        String userName = sessionUserName.get(sessionId);
        System.out.println("接收到消息：" + message+" "+sessionId+" 用户名："+userName);
    }
    @OnClose
    public void onClose(Session session) {
        System.out.println("连接关闭");
        String sessionId = session.getId();
        // 清楚会话缓存
        sessionCache.remove(sessionId);
        sessionUserName.remove(sessionId);
    }
    @OnError
    public void onError(Throwable error) {
        System.out.println("发生错误：" + error.getMessage());
    }


}
